package com.zbbt.sportslottery.ui.activity;

import java.util.ArrayList;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.bean.ColumnBean;
import com.zbbt.sportslottery.db.DbManager;
import com.zbbt.sportslottery.ui.adapter.ChannelAdapter;
import com.zbbt.sportslottery.ui.adapter.OtherAdapter;
import com.zbbt.sportslottery.ui.widget.ChannelDragGrid;
import com.zbbt.sportslottery.ui.widget.OtherDragDrid;
import com.zbbt.sportslottery.util.LogUtil;

/**
 * 
 * @ClassName: ChannelActivity
 * @Description: 频道管理
 * @author：GaomingShuo
 * @date：2015-2-4 下午1:53:27
 * @version V1.0
 */
public class ChannelActivity extends SimpleBaseActivity implements OnItemClickListener {
	// 用户栏目的gridView
	private ChannelDragGrid channelDragGrid;
	// 其他栏目的gridView
	private OtherDragDrid otherDragDrid;
	// 用户栏目的适配器 可拖动的
	private ChannelAdapter channelAdapter;
	// q其他栏目的adapter
	private OtherAdapter otherAdapter;
	// 其他栏目的列表
	private ArrayList<ColumnBean> otheritems = new ArrayList<ColumnBean>();
	// 是否被移动
	private boolean isMove = false;
	// 使用集合将数据接收
	private ArrayList<ColumnBean> channelItems = new ArrayList<ColumnBean>();

	@Override
	protected void onActivityCreated(Bundle savedInstanceState) {
		setContentView(R.layout.acttivity_channel);
	}

	@Override
	protected void initView() {
		channelDragGrid = (ChannelDragGrid) findViewById(R.id.userGridView);
		otherDragDrid = (OtherDragDrid) findViewById(R.id.otherGridView);

		for (int i = 0; i < App.userChannelList.size(); i++) {
			if (App.userChannelList.get(i).getColumnid() == 1) {
				channelItems.add(App.userChannelList.get(i));
			} else if (App.userChannelList.get(i).getColumnid() == 2) {
				otheritems.add(App.userChannelList.get(i));
			}
		}

		channelAdapter = new ChannelAdapter(this, channelItems);
		channelDragGrid.setAdapter(channelAdapter);
		otherAdapter = new OtherAdapter(this, otheritems);
		otherDragDrid.setAdapter(otherAdapter);
		// 以下方法是上下拖动item时 咋子俩个gridView中所处理的事件
		// 暂时未处理好
		// channelAdapter = new ChannelAdapter(context, channelItems);
		// channelDragGrid.setAdapter(channelAdapter);
		// channelDragGrid.setOnDragOtherListerner(new OnDragOtherListener() {
		//
		// @Override
		// public void OnDrag(int position) {
		// final ColumnBean channel = ((ChannelAdapter)
		// channelDragGrid.getAdapter()).getItem(position);
		// LogUtil.printE(TAG, "channel" + channel);
		// channelItems.remove(channel);
		// otherAdapter.isListChanged = true;
		// channelAdapter.notifyDataSetChanged();
		// otherAdapter.addItem(channel);
		// otherAdapter.notifyDataSetChanged();
		//
		// }
		// });
		//
		// // 其他栏目
		// otherAdapter = new OtherAdapter(context, otheritems);
		// otherDragDrid.setAdapter(otherAdapter);
		// otherDragDrid.setOnDragOtherListerner(new OnDragOtherListener() {
		//
		// @Override
		// public void OnDrag(int position) {
		// final ColumnBean channel = ((OtherAdapter)
		// otherDragDrid.getAdapter()).getItem(position);
		// otheritems.remove(position);
		// otherAdapter.isListChanged = true;
		// otherAdapter.notifyDataSetChanged();
		// channelAdapter.addItem(channel);
		// channelAdapter.notifyDataSetChanged();
		// }
		// });

	}

	public interface OnDragOtherListener {
		public void OnDrag(int position);
	}

	@Override
	protected void setListener() {
		channelDragGrid.setOnItemClickListener(this);
		otherDragDrid.setOnItemClickListener(this);
	}

	@Override
	protected void onClickEvent(View v) {

	}

	@Override
	protected void initData() {}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		if (isMove) {
			return;
		}
		switch (parent.getId()) {
		case R.id.userGridView:
			// 位置在第0个是 不可点击
			if (position != 0) {
				final ImageView imageView = getView(view);
				if (imageView != null) {
					TextView textView = (TextView) view.findViewById(R.id.text_item);
					final int[] startLocation = new int[2];
					textView.getLocationInWindow(startLocation);

					// 获取点击的频道内容
					final ColumnBean channel = ((ChannelAdapter) parent.getAdapter()).getItem(position);
					LogUtil.printD(TAG, "position" + position);
					otherAdapter.setVisible(false);
					// 添加到最后一个
					otherAdapter.addItem(channel);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							try {
								int[] endLocation = new int[2];
								// 获取最终的位置
								otherDragDrid.getChildAt(otherDragDrid.getLastVisiblePosition())
										.getLocationInWindow(endLocation);
								MoveAnim(imageView, startLocation, endLocation, channel, channelDragGrid);
								// 删除之后的position
								channelAdapter.setRemove(position);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}, 50L);
				}
			}
			break;

		case R.id.otherGridView:
			final ImageView otherImageView = getView(view);
			if (otherImageView != null) {
				TextView textView = (TextView) view.findViewById(R.id.text_item);
				final int[] startLocatin = new int[2];
				textView.getLocationInWindow(startLocatin);
				final ColumnBean channelItem = ((OtherAdapter) parent.getAdapter()).getItem(position);
				channelAdapter.setVisible(false);
				// 添加到最后一个
				channelAdapter.addItem(channelItem);
				new Handler().postDelayed(new Runnable() {
					public void run() {
						try {
							final int[] endLocation = new int[2];
							// 获取终点的坐标
							channelDragGrid.getChildAt(channelDragGrid.getLastVisiblePosition())
									.getLocationInWindow(endLocation);
							MoveAnim(otherImageView, startLocatin, endLocation, channelItem, otherDragDrid);
							otherAdapter.setRemove(position);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}, 50L);
			}

			break;
		}

	}

	/**
	 * 获取点击的Item的对应View，
	 * 
	 * @param view
	 * @return
	 */
	private ImageView getView(View view) {
		view.destroyDrawingCache();
		view.setDrawingCacheEnabled(true);
		Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
		view.setDrawingCacheEnabled(false);
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(cache);
		return iv;
	}

	/**
	 * 
	 * @MethodName:MoveAnim
	 * @Description: 点击item移动时的动画
	 * @author：GaomingShuo
	 * @date：2015-2-5 下午2:42:21 void
	 */
	private void MoveAnim(View moveView, int[] startLocation, int[] endLocation,
			final ColumnBean moveChannel, final GridView clickGridView) {
		int[] initLocation = new int[2];
		// 获取传过来的item 的坐标
		moveView.getLocationInWindow(initLocation);
		// 得到移动时的View 放进相应的容器中去
		final ViewGroup moveViewGroup = getMoveViewGroup();
		final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
		// 创建移动动画
		TranslateAnimation moveAnimation = new TranslateAnimation(startLocation[0], endLocation[0],
				startLocation[1], endLocation[1]);
		moveAnimation.setDuration(300L);// 动画时间
		AnimationSet animationSet = new AnimationSet(true);
		animationSet.setFillAfter(false);// 动画效果执行完毕后，View对象不保留在终止的位置
		animationSet.addAnimation(moveAnimation);
		mMoveView.startAnimation(animationSet);
		animationSet.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				isMove = true;

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {

				moveViewGroup.removeView(mMoveView);
				// instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
				if (clickGridView instanceof ChannelDragGrid) {
					otherAdapter.setVisible(true);
					otherAdapter.notifyDataSetChanged();
					channelAdapter.remove();
				} else {
					channelAdapter.setVisible(true);
					channelAdapter.notifyDataSetChanged();
					otherAdapter.remove();
				}
				isMove = false;

			}
		});
	}

	/**
	 * 
	 * @MethodName:getMoveView
	 * @Description: 获取移动的VIEW，放入对应ViewGroup布局容器
	 * @author：GaomingShuo
	 * @date：2015-2-5 下午2:59:20
	 * @param viewGroup
	 * @param view
	 * @param initLocation
	 * @return View
	 */
	private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
		int X = initLocation[0];
		int Y = initLocation[1];
		viewGroup.addView(view);
		LinearLayout.LayoutParams mlayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
		mlayoutParams.leftMargin = X;
		mlayoutParams.topMargin = Y;
		view.setLayoutParams(mlayoutParams);

		return view;
	}

	/**
	 * 
	 * @MethodName:getMoveViewGroup
	 * @Description: 创建移动的item 所对应ViewGroup容器布局
	 * @author：GaomingShuo
	 * @date：2015-2-5 下午2:47:05
	 * @return ViewGroup
	 */
	private ViewGroup getMoveViewGroup() {
		// 次方法相当于是临时创建一个小型的窗口
		ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
		LinearLayout moveLinearLayout = new LinearLayout(this);
		moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		moveViewGroup.addView(moveLinearLayout);

		return moveLinearLayout;

	}

	/**
	 * 
	 * @MethodName:savaChannel
	 * @Description: 退出时 保存数据
	 * @author：GaomingShuo
	 * @date：2015-2-5 下午7:31:25 void
	 */
	private void savaChannel() {
		App.userChannelList.clear();
		for (int i = 0; i < channelItems.size(); i++) {
			channelItems.get(i).setColumnid(1);
			App.userChannelList.add(channelItems.get(i));
		}
		for (int i = 0; i < otheritems.size(); i++) {
			otheritems.get(i).setColumnid(2);
			App.userChannelList.add(otheritems.get(i));
		}
		DbManager.savaChannel(App.userChannelList);
	}

	@Override
	public void onBackPressed() {
		savaChannel();
		setResult(App.CHANNELRESULT = 2);
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
	}

}
